import React from 'react';
import { connect } from 'react-redux';
import { login } from '../../actions/authActions';
import { Form, Icon, Input, Button, Checkbox } from 'antd';
const FormItem = Form.Item;

class AdminLoginForm extends React.Component {
  constructor(props){
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.login(values).then(
          (res) =>{  this.context.router.push('/admin/dashboard') },
          (err) => { this.setState({ errors: "", isLoading: false }) }
         );
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <FormItem>
          {getFieldDecorator('email', {
            rules: [{ required: true, message: 'Please input your email!' }],
          })(
            <Input addonBefore={<Icon type="username" />} placeholder="Email" />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: 'Please input your Password!' }],
          })(
            <Input addonBefore={<Icon type="lock" />} type="password" placeholder="Password" />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('remember', {
            valuePropName: 'checked',
            initialValue: true,
          })(
            <Checkbox>Remember me</Checkbox>
          )}
          <Button type="primary" htmlType="submit" className="login-form-button">
            Log in
          </Button>
        </FormItem>
      </Form>
    );
  }
}

AdminLoginForm.propTypes = {
  login: React.PropTypes.func.isRequired
}

AdminLoginForm.contextTypes = {
  router: React.PropTypes.object.isRequired
}

export default connect(null, { login })(Form.create()(AdminLoginForm));